<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Storage;
use Event;
use App\Events\debug\Debug;
use App\Events\log\AllLog;
use App\Events\noti\Inform;
use App\Models\Area;
use App\Models\Building;
use App\Models\Room;
use Cache;

class NBSmokeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $info = $request -> all();
        /*$info = '{
       "notifyType":"deviceDatasChanged",
       "requestId":null,
       "deviceId":"e023fea4-6e29-41e1-8b92-1bf47134335a",
       "gatewayId":"e023fea4-6e29-41e1-8b92-1bf47134335a",
       "services":[
           {
               "serviceId":"SQVH75",
               "serviceType":"SQVH75",
               "data":{
                   "Alarm_on":0,
                   "Alarm_fire":0,
                   "Alarm_check":0,
                   "Alarm_battery":0,
                   "Alarm_fault":0,
                   "Base_apart":1,
                   "Base_lost":0,
                   "Base_temperature":0,
                   "Base_battery":0,
                   "Base_Other":0
                   },
               "eventTime":"20180411T042956Z"
               }
           ]
       }';*/
        $where = array();
        $where['nd.deviceId'] = $info['deviceId'];
        //查询qy_smoke表,获取设备信息
        $msg = DB::table('nb_bind as nb')
            -> leftJoin('nb_device as nd','nd.verifyCode','=','nb.verifyCode')
            -> leftJoin('room as r','nb.room_id','=','r.id')
            -> leftJoin('building as b','r.building_id','=','b.id')
            -> leftJoin('area as a','b.area_id','=','a.id')
            -> leftJoin('camera as c','nb.camera_id','=','c.id')
            -> select('nb.agent_id','nb.verifyCode as num','nb.status','nb.room_id','nb.loc','r.name as rname','r.building_id','b.name as bname','b.latitude','b.longitude','b.area_id','a.name as aname','c.url')
            -> where($where)
            -> first();
        //设备类型
        $devType = $info['services'][0]['serviceType'];
        switch ($devType) {
            case 'SQVH75':
                $msg['type'] = '烟感';
                break;

            default:
                $msg['type'] = '其他';
                break;
        }
        //报警类型
        $warning = array_search(1,$info['services'][0]['data']);
        if($warning){
            switch ($warning) {
                case 'Alarm_on':
                    $msg['genre'] = '开机';
                    break;
                case 'Alarm_fire':
                    $msg['genre'] = '火灾';
                    break;
                case 'Alarm_check':
                    $msg['genre'] = '自检';
                    break;
                case 'Alarm_battery':
                    $msg['genre'] = '电量';
                    break;
                case 'Alarm_fault':
                    $msg['genre'] = '故障';
                    break;
                case 'Base_apart':
                    $msg['genre'] = '底座防拆';
                    break;
                case 'Base_lost':
                    $msg['genre'] = '底座失联';
                    break;
                case 'Base_temperature':
                    $msg['genre'] = '底座温度';
                    break;
                case 'Base_battery':
                    $msg['genre'] = '底座电量';
                    break;
                default:
                    $msg['genre'] = '底座其他';
                    break;
            }

            //用户信息
            $users = array();
            $busers = array();
            $users['bemail'] = array();
            $users['bphone'] = array();
            $users['bmobile'] = array();
            $noti = DB::table('noti_set')->get();
            // 获取用户信息
            // $area = Area::where('id',$msg['area_id'])->first()->member()->orderBy('name')->get();
            $area = Area::where('id',$msg['area_id']) -> first();
            if ( (!empty($area)) && (!empty($area->member)) ){
                foreach ($area->member as $areaUsers) {
                    if ($areaUsers->name) {
                        array_push($busers,$areaUsers->name);
                    }
                    // 邮箱
                    if (($noti['2']['noti_area']==1)&&($areaUsers->email)) {
                        array_push($users['bemail'],$areaUsers->email);
                    }
                    // 短信
                    if (($noti['0']['noti_area']==1)&&($areaUsers->phone)) {
                        array_push($users['bphone'],$areaUsers->phone);
                    }
                    // 语音
                    if (($noti['1']['noti_area']==1)&&($areaUsers->phone)) {
                        array_push($users['bmobile'],$areaUsers->phone);
                    }
                }
            }
            $building = Building::where('id',$msg['building_id'])->first();
            if( (!empty($building) ) && (!empty($building->member)) ) {
                foreach ($building->member as $buildingUsers) {
                    if ($buildingUsers->name) {
                        array_push($busers,$buildingUsers->name);
                    }
                    // 邮件
                    if (($noti['2']['noti_building']==1)&&($buildingUsers->email)) {
                        array_push($users['bemail'],$buildingUsers->email);
                    }
                    // 短信
                    if (($noti['0']['noti_building']==1)&&($buildingUsers->phone)) {
                        array_push($users['bphone'],$buildingUsers->phone);
                    }
                    // 语音
                    if (($noti['1']['noti_building']==1)&&($buildingUsers->phone)) {
                        array_push($users['bmobile'],$buildingUsers->phone);
                    }
                }
            }
            $room = Room::where('id',$msg['room_id'])->first();
            if( (!empty($room)) && (!empty($room->member)) ) {
                foreach ($room->member as $roomUsers) {
                    if ($roomUsers->name) {
                        array_push($busers,$roomUsers->name);
                    }
                    // 邮件
                    if (($noti['2']['noti_room']==1)&&($roomUsers->email)) {
                        array_push($users['bemail'],$roomUsers->email);
                    }
                    // 短信
                    if (($noti['0']['noti_room']==1)&&($roomUsers->phone)) {
                        array_push($users['bphone'],$roomUsers->phone);
                    }
                    // 语音
                    if (($noti['1']['noti_room']==1)&&($roomUsers->phone)) {
                        array_push($users['bmobile'],$roomUsers->phone);
                    }
                }
            }

            // workerman
            $msg['user'] = array_pop($busers);
            $userphone = $users['bphone'];
            // $msgdata['phone'] = substr_replace(array_pop($userphone),"****",3,4);
            $msg['phone'] = array_pop($userphone);
            $data_json = json_encode($msg);
            unset($msg['user'],$msg['phone']);
            // 指明给谁推送，为空表示向所有在线用户推送
            $to_uid = "new";
            // 推送的url地址，使用自己的服务器地址
            $push_api_url = "http://127.0.0.1:2121/";
            $post_data = array(
                "type" => "publish",
                "content" => $data_json,
                "to" => $to_uid,
            );
            $ch = curl_init ();
            curl_setopt ( $ch, CURLOPT_URL, $push_api_url );
            curl_setopt ( $ch, CURLOPT_POST, 1 );
            curl_setopt ( $ch, CURLOPT_HEADER, 0 );
            curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
            curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Expect:"));
            $return = curl_exec ( $ch );
            curl_close ( $ch );
            var_export($return);

            // 通知
            Event::fire(new Inform($msg,$users,$noti));

            //将原始数据写入数据库
            $raw = $info['services'][0]['data'];
            $raw['deviceId'] = $info['deviceId'];
            DB::table('profile_'.strtolower($info['services'][0]['serviceType']))
                -> insert($raw);
            //写入运营报表
            DB::table('nb_report') -> insert(['verifyCode'=>$msg['num'],'type_name'=>$devType,'loc'=>$msg['aname'].$msg['bname'].$msg['rname'],'addTime'=>time()]);
        }
    }
}
